package util;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ArrayUtil {
	private static final Log LOG = LogFactory.getLog(ArrayUtil.class);

	public static String[] splice(String[] arr, int start, int end) {

		if (arr == null || arr.length == 0) {
			return new String[] { "" };
		}
		if (start < 0) {
			start = arr.length - (-1 * start);
		}
		if (end < 0) {
			end = arr.length - (-1 * end);
		}
		String[] newArr = new String[end - start];
		for (int tmp = start, i = 0; tmp < end; tmp++, i++) {
			newArr[i] = arr[tmp];
		}
		return newArr;

	}

	public static String join(Object[] arr, String joinChar) {
		if (arr == null || arr.length == 0) {
			return "";
		}
		StringBuilder buffer = new StringBuilder();
		for (Object o : arr) {
			buffer.append(o == null ? "" : o.toString() + joinChar);
		}
		buffer.setLength(buffer.length() - 1);
		return buffer.toString();
	}

	@SuppressWarnings("unchecked")
	public static String join(List values, String joinChar) {
		if (joinChar == null) {
			return joinC(values, ",");
		} else {
			return joinC(values, joinChar);
		}
	}

	public static String joinC(Iterable<? extends Object> values,
			String joinChar) {
		if (values == null) {
			return "";
		}
		StringBuilder buffer = new StringBuilder();
		// int i=0;
		for (Object o : values) {
			// LOG.error("Counter = "+ (++i) );
			buffer.append((o == null ? "" : o.toString()) + joinChar);
		}
		buffer.setLength(buffer.length() - 1);
		return buffer.toString();
	}

	public static String joinUniqueC(Iterable<? extends Object> values,
			String joinChar) {
		if (values == null) {
			return "";
		}
		StringBuilder buffer = new StringBuilder();
		// int i=0;
		Set<Object> valsSet = new HashSet<Object>();
		for (Object o : values) {
			// LOG.error("Counter = "+ (++i) );
			if (valsSet.add(o)) {
				buffer.append((o == null ? "" : o.toString()) + joinChar);
			}
		}
		buffer.setLength(buffer.length() - 1);
		return buffer.toString();
	}
}
